const fs = require('fs')

// 发布-订阅
const EventEmitter = require('events')
const ev = new EventEmitter()

console.info(' ---------------- on ---------------- ')

// on
ev.on('event_1', () => {
  console.info('event_1 执行了 --- 3')
})

ev.on('event_1', () => {
  console.info('event_1 执行了 --- 1')
})

ev.on('event_1', () => {
  console.info('event_1 执行了 --- 2')
})

// emit
ev.emit('event_1')
ev.emit('event_1') // 🚀 多次执行

console.info(' ---------------- once ---------------- ')

ev.once('event_2', () => {
  console.info('event_2 执行了 --- 1')
})
ev.once('event_2', () => {
  console.info('event_2 执行了 --- 2')
})

ev.emit('event_2') // 🚀 执行一次
ev.emit('event_2') // 🚀 这次不执行

console.info(' ---------------- off ---------------- ')
let cbFn = (...args) => {
  console.info('event_3 执行了')
  console.info('args', args)
}

ev.on('event_3', cbFn)
ev.emit('event_3', 1, 2, 3)

ev.off('event_3', cbFn) // 取消事件
ev.emit('event_3') // 不会执行了

console.info(' ---------------- event array ---------------- ')
/**
 * 箭头函数的 this: {} => 空对象
 */
ev.on('event_4', function () {
  /**   >>>> this >>>>
    EventEmitter {
        _events: [Object: null prototype] {
            event_1: [ [Function], [Function], [Function] ], ===> event_1 有3个监听事件
            event_4: [Function] ===> event_4 有1个监听事件
        },
        _eventsCount: 2,
        _maxListeners: undefined,
        [Symbol(kCapture)]: false
    }
    */
  console.info(this)
  console.info('event_4 执行了')
})
ev.emit('event_4')

console.info(' ---------------- event other ---------------- ')
const crt = fs.createReadStream()
crt.on('data')
/**
 *  on(event: "close", listener: () => void): this;
    on(event: "data", listener: (chunk: Buffer | string) => void): this;
    on(event: "end", listener: () => void): this;
    on(event: "error", listener: (err: Error) => void): this;
    on(event: "open", listener: (fd: number) => void): this;
    on(event: "pause", listener: () => void): this;
    on(event: "readable", listener: () => void): this;
    on(event: "ready", listener: () => void): this;
    on(event: "resume", listener: () => void): this;
    on(event: string | symbol, listener: (...args: any[]) => void): this;
 */
// event-loop: 每次触发事件完成, 回调会被push到 loop里
